#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "segment.h"
#include "imgutil.h"
#include "mathutil.h"
#include "quan.h"
#include "memutil.h"
#include "global.h"

float	TQUAN, threshcolor;
int		NSCALE, NY, NX;


__declspec(dllexport) int ProcessImage
(
	unsigned char	*inputImage,
	int				inputImageHeight,
	int				inputImageWidth,
	unsigned char	*colorMap,
	unsigned char	*regionMap,
	int				colorQuantizationThreshold,
	int				numberOfScales,
	float			regionMergeThreshold,
	int				mode,
	void (_stdcall *ReportMethod)(unsigned char* str),
	void (_stdcall *ShowJImage)(int i, float * J, int height, int width))
{
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	unsigned char	*RGB, *cmap, *RGB2;
	int				dim, N, i, j, k, TR, imgsize, mapsize, l;
	float			*LUV, **cb;
	unsigned char	*rmap;
	/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

	outReport = ReportMethod;
	outShowJImage = ShowJImage;
	method_mode = mode;

	NY = inputImageHeight;
	NX = inputImageWidth;				

	TQUAN = colorQuantizationThreshold; /* 0-600, default -1 */
	NSCALE = numberOfScales;			/* >0, default -1 */
	threshcolor = regionMergeThreshold; /* 0-1.0, default 0.4 */

	dim = 3;					// number of components RGB
	imgsize = NY * NX * dim;
	mapsize = NY * NX * 1;

	RGB = (unsigned char *) malloc(imgsize * sizeof(unsigned char));
	LUV = (float *) malloc(imgsize * sizeof(float));
	cb = (float **) fmatrix(256, dim);	
	cmap = (unsigned char *) calloc(mapsize, sizeof(unsigned char));
	rmap = (unsigned char *) calloc(mapsize, sizeof(unsigned char));

	for(i = 0; i < imgsize; i++)
	{
		RGB[i] = inputImage[i];
	}
	
	Report("rgb 2 luv");
	// Conversion of color system
	rgb2luv(RGB, LUV, imgsize);

	// Color quantization
	Report("Color quantization");
	N = quantize(LUV, cb, NY, NX, dim, TQUAN);

	Report("Get color map");
	getcmap(LUV, cmap, cb, mapsize, dim, N);

	free_fmatrix(cb, 256);
	free(LUV);

	Report("Segment");
	TR = segment
		(
			rmap,
			cmap,
			N,
			NY,
			NX,
			dim,
			NSCALE
		);
	
	Report("Merge rmap and cmap");
	TR = merge1(rmap, cmap, N, NY, NX, TR, threshcolor);
	
	for(i = 0; i < mapsize; i++)
	{
		colorMap[i] = cmap[i];
	}

	for(i = 0; i < mapsize; i++)
	{
		regionMap[i] = rmap[i];
	}

	free(cmap);
	free(RGB);
	free(rmap);

	return 0;
}

